{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From d:\\dev\\ai\\anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\base.py:198: retry (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use the retry module or similar alternatives.\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import tensorflow.contrib.slim as slim\n",
    "from tensorflow.examples.tutorials.mnist import input_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-698ada706af1>:3: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From d:\\dev\\ai\\anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From d:\\dev\\ai\\anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From d:\\dev\\ai\\anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From d:\\dev\\ai\\anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From d:\\dev\\ai\\anaconda2\\envs\\python3\\lib\\site-packages\\tensorflow\\contrib\\learn\\python\\learn\\datasets\\mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#neuron num\n",
    "lamda = 0.0001 #正则超参数\n",
    "learning_rate_ = 0.15\n",
    "learning_rate_decay = 0.95\n",
    "KN1 = 64\n",
    "KS1 = 9\n",
    "KN2 = 128\n",
    "KS2 = 9"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "学习率：虽然设置了学习率衰减，但初始值还是保持在0.2以内才能收敛，似乎比多层神经网络更容易梯度爆炸？\n",
    "\n",
    "正则超参数：按照学习到最后的loss可以看出目前的这个值还比较合适\n",
    "\n",
    "核数量：减半后发现收敛更快，但是精度下降比较明显，所以又调成原本的两倍，目前学习速度变慢了许多，但效果更好\n",
    "\n",
    "核大小：3x3 5x5 7x7 9x9都试了试，大小提高，训练的速度下降非常明显，但精度有所提高。77到99时训练到最后，过拟合问题似乎加剧了，以至于测试集精度没有提高\n",
    "\n",
    "初始值：都才用了高斯随机数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define loss and optimizer\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "\n",
    "#变形成28x28\n",
    "with tf.name_scope('reshape'):\n",
    "  x_image = tf.reshape(x, [-1, 28, 28, 1])\n",
    "\n",
    "initializer = tf.truncated_normal_initializer(stddev=0.01)\n",
    "regularizer = slim.l2_regularizer(lamda)\n",
    "\n",
    "\n",
    "# 进行卷积，卷积核数量32\n",
    "with tf.name_scope('conv1'):\n",
    "  h_conv1 = tf.contrib.slim.conv2d(\n",
    "      x_image, KN1, [KS1,KS1],\n",
    "      padding='SAME',\n",
    "      activation_fn=tf.nn.relu,\n",
    "      weights_initializer=initializer,\n",
    "      weights_regularizer=regularizer)\n",
    "\n",
    "\n",
    "# 2x2池化\n",
    "with tf.name_scope('pool1'):\n",
    "  h_pool1 = tf.contrib.slim.max_pool2d(h_conv1, [2,2], stride=2, \n",
    "                         padding='VALID')\n",
    "\n",
    "# 再次卷积，64核\n",
    "with tf.name_scope('conv2'):\n",
    "  h_conv2 = tf.contrib.slim.conv2d(\n",
    "      h_pool1, KN2, [KS2,KS2],\n",
    "      padding='SAME',\n",
    "      weights_initializer=initializer,\n",
    "      weights_regularizer=regularizer,\n",
    "      activation_fn=tf.nn.relu)\n",
    "\n",
    "# 2x2池化\n",
    "with tf.name_scope('pool2'):\n",
    "  h_pool2 = tf.contrib.slim.max_pool2d(h_conv2, [2,2],\n",
    "                        stride=[2, 2], padding='VALID')\n",
    "\n",
    "# 用1x1卷积变成1024向量\n",
    "with tf.name_scope('fc1'):\n",
    "  h_pool2_reshape = tf.reshape(h_pool2,[-1,7*7*KN2])#[N,7*7*64]  \n",
    "  #h_pool2_flat = tf.contrib.slim.flatten(h_pool2)\n",
    "#   h_fc1 = tf.contrib.slim.conv2d(\n",
    "#       h_pool2, 1024, [7,7], \n",
    "#       weights_initializer=initializer,\n",
    "#       weights_regularizer=regularizer, \n",
    "#       activation_fn=tf.nn.relu)\n",
    "  h_fc1 = slim.fully_connected(h_pool2_reshape,1024,weights_initializer=initializer,scope='fc1')#shape of net is [N,1024]  \n",
    "# Dropout - controls the complexity of the model, prevents co-adaptation of\n",
    "# features.\n",
    "with tf.name_scope('dropout'):\n",
    "  keep_prob = tf.placeholder(tf.float32)\n",
    "  h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "\n",
    "# Map the 1024 features to 10 classes, one for each digit\n",
    "with tf.name_scope('fc2'):\n",
    "#   y = tf.squeeze(tf.contrib.slim.conv2d(h_fc1_drop, 10, [1,1], \n",
    "#         weights_initializer=initializer,\n",
    "#         weights_regularizer=regularizer, activation_fn=None))\n",
    "  y = slim.fully_connected(h_fc1_drop,10,weights_initializer=initializer,scope='fc2')#[N,10]  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-5-599b4bc928ea>:10: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See tf.nn.softmax_cross_entropy_with_logits_v2.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "#\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)] )\n",
    "total_loss = cross_entropy + lamda*l2_loss\n",
    "#slim.losses.add_loss(cross_entropy)\n",
    "\n",
    "#total_loss = slim.losses.get_total_loss(add_regularization_losses=True)\n",
    "\n",
    "# 定义学习率衰减\n",
    "global_step = tf.Variable(0)\n",
    "learning_rate = tf.train.exponential_decay(learning_rate_,global_step,100,learning_rate_decay,staircase=True)\n",
    "\n",
    "\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss,global_step=global_step)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 100, entropy loss: 1.892276, l2_loss: 275.945953, total loss: 1.919870\n",
      "0.52\n",
      "step 200, entropy loss: 0.286241, l2_loss: 286.733612, total loss: 0.314914\n",
      "0.94\n",
      "step 300, entropy loss: 0.384250, l2_loss: 290.307190, total loss: 0.413281\n",
      "0.91\n",
      "step 400, entropy loss: 0.227928, l2_loss: 292.401794, total loss: 0.257168\n",
      "0.98\n",
      "step 500, entropy loss: 0.164677, l2_loss: 293.762726, total loss: 0.194054\n",
      "0.97\n",
      "step 600, entropy loss: 0.077592, l2_loss: 294.976318, total loss: 0.107089\n",
      "1.0\n",
      "step 700, entropy loss: 0.080264, l2_loss: 295.746307, total loss: 0.109839\n",
      "1.0\n",
      "step 800, entropy loss: 0.117062, l2_loss: 296.426086, total loss: 0.146705\n",
      "0.97\n",
      "step 900, entropy loss: 0.052475, l2_loss: 297.039978, total loss: 0.082179\n",
      "1.0\n",
      "step 1000, entropy loss: 0.041961, l2_loss: 297.261902, total loss: 0.071687\n",
      "1.0\n",
      "0.9827\n",
      "step 1100, entropy loss: 0.111020, l2_loss: 297.644501, total loss: 0.140784\n",
      "0.99\n",
      "step 1200, entropy loss: 0.074503, l2_loss: 297.943359, total loss: 0.104298\n",
      "0.97\n",
      "step 1300, entropy loss: 0.087976, l2_loss: 298.254730, total loss: 0.117801\n",
      "0.99\n",
      "step 1400, entropy loss: 0.065130, l2_loss: 298.414154, total loss: 0.094972\n",
      "0.99\n",
      "step 1500, entropy loss: 0.037442, l2_loss: 298.464386, total loss: 0.067288\n",
      "0.99\n",
      "step 1600, entropy loss: 0.052523, l2_loss: 298.521027, total loss: 0.082375\n",
      "1.0\n",
      "step 1700, entropy loss: 0.025477, l2_loss: 298.638397, total loss: 0.055341\n",
      "1.0\n",
      "step 1800, entropy loss: 0.059423, l2_loss: 298.708588, total loss: 0.089294\n",
      "1.0\n",
      "step 1900, entropy loss: 0.022941, l2_loss: 298.821503, total loss: 0.052824\n",
      "1.0\n",
      "step 2000, entropy loss: 0.059615, l2_loss: 298.834869, total loss: 0.089499\n",
      "1.0\n",
      "0.987\n",
      "step 2100, entropy loss: 0.027585, l2_loss: 298.838593, total loss: 0.057469\n",
      "1.0\n",
      "step 2200, entropy loss: 0.095204, l2_loss: 298.851379, total loss: 0.125089\n",
      "0.99\n",
      "step 2300, entropy loss: 0.038276, l2_loss: 298.876984, total loss: 0.068164\n",
      "1.0\n",
      "step 2400, entropy loss: 0.046843, l2_loss: 298.913208, total loss: 0.076734\n",
      "0.99\n",
      "step 2500, entropy loss: 0.064621, l2_loss: 298.888275, total loss: 0.094510\n",
      "0.97\n",
      "step 2600, entropy loss: 0.003688, l2_loss: 298.923370, total loss: 0.033580\n",
      "1.0\n",
      "step 2700, entropy loss: 0.005505, l2_loss: 298.888794, total loss: 0.035394\n",
      "1.0\n",
      "step 2800, entropy loss: 0.016650, l2_loss: 298.901245, total loss: 0.046541\n",
      "1.0\n",
      "step 2900, entropy loss: 0.015766, l2_loss: 298.874969, total loss: 0.045653\n",
      "1.0\n",
      "step 3000, entropy loss: 0.037024, l2_loss: 298.848267, total loss: 0.066909\n",
      "0.99\n",
      "0.9884\n"
     ]
    }
   ],
   "source": [
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n",
    "# Train\n",
    "for step in range(3000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  _, loss, l2_loss_value, total_loss_value = sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, keep_prob:0.5})\n",
    "  \n",
    "  if (step+1) % 100 == 0:\n",
    "    print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    # Test trained model\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob:0.5}))\n",
    "  if (step+1) % 1000 == 0:\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels, keep_prob:0.5}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
